package com.ndp.fb.mq.producer;

import com.alibaba.dubbo.config.annotation.Reference;
import com.ndp.fb.constant.CommonConstants;
import com.ndp.fb.enums.message.EventNotificationType;
import com.ndp.fb.model.fbagent.param.ApiCallBackTarget;
import com.ndp.fb.mq.api.producer.PushNotificationProducerService;
import com.ndp.fb.mq.api.producer.RocketMqProducerService;
import com.ndp.fb.rdb.api.UserRdbServices;
import com.ndp.fb.rdb.model.User;
import com.ndp.fb.rdb.model.message.EventNotificationMessage;
import com.ndp.fb.redis.api.RedisDistributedLockService;
import com.ndp.fb.util.UUID;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * Created by elvisxiong on 7/24/15.
 */
@Component
@Qualifier("webSocketPushNotificationProducerService")
public class WebSocketPushNotificationProducerServiceImpl implements PushNotificationProducerService {

    private static final Logger Log = LoggerFactory.getLogger(WebSocketPushNotificationProducerServiceImpl.class);

    @Autowired
    RocketMqProducerService rocketMqProducerService;
    @Reference
    UserRdbServices userRdbServices;
    @Autowired
    RedisDistributedLockService redisDistributedLockService;

    @Override
    public void sendPushNotifiction(EventNotificationMessage message) {
        ApiCallBackTarget.Target target = ApiCallBackTarget.WebPush.WebSocketPushNotification;
        EventNotificationType eventNotificationType = message.getEventType();
        if(eventNotificationType != null){
            String title = eventNotificationType.getName();
            String receiver = message.getReceiver();
            try {
                if (redisDistributedLockService.tryLock(CommonConstants.BADAGE_NUM_LOCK + receiver, 1, TimeUnit.MINUTES)) {
                    User user = userRdbServices.getUserByTicket(receiver);
                    if (user != null) {
                        user.setBadgeNum(user.getBadgeNum() + 1);
                        userRdbServices.update(user);
                        rocketMqProducerService.sendMessage(target.getModuleName(), target.getTargetType(), UUID.get(),
                                new Object[]{message.getId(), receiver, eventNotificationType.getType(), title, null, message.isNeedFunctionJump(), message.getUrl(),
                                        user.getBadgeNum(),message.getEventKey(),message.getEventValues()});
                    }
                }
            } catch (Exception ex) {
                Log.error(ex.getMessage(), ex);
            } finally {
                redisDistributedLockService.unLock(CommonConstants.BADAGE_NUM_LOCK + receiver);
            }
        }
    }
}
